<?php

namespace KingBes\Thread;

use \FFI\CData;

class Thread
{
    private \FFI $ffi;

    private CData $thread;

    /**
     * 构造函数
     * @throws \Exception
     */
    public function __construct()
    {
        $header = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Thread.h');
        if (PHP_OS_FAMILY === 'Windows') {
            $suffix = '.dll';
        } else if (PHP_OS_FAMILY === 'Linux') {
            $suffix = '.so';
        } else {
            throw new \Exception('不支持的操作系统:' . PHP_OS_FAMILY);
        }
        $lib = dirname(__DIR__)
            . DIRECTORY_SEPARATOR . 'lib'
            . DIRECTORY_SEPARATOR . 'Thread' . $suffix;
        $this->ffi = \FFI::cdef($header, $lib);
        $this->thread = $this->ffi->thread_create();
    }

    /**
     * 执行任务
     *
     * @param callable $callback 回调函数
     * @return void
     */
    public function spawn(callable $callback): void
    {
        $function = function () use ($callback) {
            $callback();
        };
        $this->ffi->thread_spawn($this->thread, $function);
    }

    /**
     * 等待任务执行完毕
     *
     * @return void
     */
    public function wait(): void
    {
        $this->ffi->thread_wait($this->thread);
    }
}
